 /**
 * Description: 物资归还记录
 * @author:Hunter
 * @since:1.0.0
 *
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2018-04-08   Hunter       1.0.0     Initial
 */
package com.metro.paperless.app.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.metro.core.dao.IMapper;
import com.metro.core.service.BaseServiceSupport;
import com.metro.core.service.ServiceException;
import com.metro.core.vo.JsonResult;
import com.metro.core.vo.ResultCode;
import com.metro.core.vo.inf.IResult;
import com.metro.paperless.app.beans.vo.AppLendDetail;
import com.metro.paperless.app.beans.vo.AppMaterialsLend;
import com.metro.paperless.app.beans.vo.AppMaterialsReturn;
import com.metro.paperless.app.beans.vo.AppReturnDetail;
import com.metro.paperless.app.beans.vo.AppReturnDetailForm;
import com.metro.paperless.app.mapper.IAppLendDetailMapper;
import com.metro.paperless.app.mapper.IAppMaterialsLendMapper;
import com.metro.paperless.app.mapper.IAppMaterialsReturnMapper;
import com.metro.paperless.app.mapper.IAppReturnDetailMapper;
import com.metro.paperless.app.service.inf.IAppLendDetailService;
import com.metro.paperless.app.service.inf.IAppMaterialsLendService;
import com.metro.paperless.app.service.inf.IAppMaterialsReturnService;
import com.metro.paperless.biz.beans.vo.BizMaterialsManage;
import com.metro.paperless.biz.mapper.IBizMaterialsManageMapper;
import com.metro.paperless.biz.service.inf.IBizMaterialsManageService;

import lombok.experimental.PackagePrivate;

 /**
 * 物资归还记录<br>
 *
 * @author:Hunter
 * @since:1.0.0
 * @version [1.0.0, 2018-04-08]
 */
@Service("appmaterialsreturnService")
public class AppMaterialsReturnService extends BaseServiceSupport<AppMaterialsReturn> implements IAppMaterialsReturnService{
    //物资归还记录Mapper
    @Autowired
    private IAppMaterialsReturnMapper appmaterialsreturnMapper;
    
    @Autowired
    private IAppReturnDetailMapper appReturnDetailMapper;
    
//    @Autowired
//    private IAppLendDetailService appLendDetailService;
    @Autowired
    private IAppLendDetailMapper appLendDetailMapper;
    
    @Autowired
    private IBizMaterialsManageMapper materialsManageMapper;
//    @Autowired
//    private IBizMaterialsManageService materialsManageService;

    @Autowired
    private IAppMaterialsLendService appMaterialsLendService;

    @SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
    public IMapper getMapper() {
        return appmaterialsreturnMapper;
    }

    @Override
    public IResult save(AppMaterialsReturn entity) {
        try {
            appmaterialsreturnMapper.save(entity);
            return ResultCode.SUCCESS;
        } catch (Exception e) {
            log.error("新增物资归还记录失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
    }

    @Override
    public IResult update(AppMaterialsReturn entity) {
        try {
            appmaterialsreturnMapper.update(entity);
            return ResultCode.SUCCESS;
        } catch (Exception e) {
            log.error("修改物资归还记录失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
    }

    @Override
    public IResult delete(Long id) {
        try {
            appmaterialsreturnMapper.delete(id);
            return ResultCode.SUCCESS;
        } catch (Exception e) {
            log.error("删除失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
    }

    @Override
    public IResult deleteByIds(String ids) {
        try {
            appmaterialsreturnMapper.deleteByIds(ids);
            return ResultCode.SUCCESS;
        } catch (Exception e) {
            log.error("删除失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
    }

	@Override
	public List<AppMaterialsReturn> queryListByLendId(Long lendId) {
		return appmaterialsreturnMapper.queryListByLendId(lendId);
	}

	@Override
	public IResult save(AppReturnDetailForm form, AppMaterialsReturn entity) {
		try {
            entity.setReturnTime(new Date());
            //保存时设置状态为0 待归还
            entity.setReturnStatus("0");
            appmaterialsreturnMapper.save(entity);
            
            for (AppReturnDetail itementity : form.getItemEntity()) {
            	itementity.setReturnId(entity.getId());
                appReturnDetailMapper.save(itementity);
                
                // 获取对应的借出明细
//                AppLendDetail queryEntity = new AppLendDetail();
//                queryEntity.setLendId(entity.getLendId());
//                queryEntity.setMaterialsId(itementity.getMaterialsId());
//                AppLendDetail lendDetail = appLendDetailService.queryForList(queryEntity).get(0);
//                lendDetail.setNeedReturnNum(lendDetail.getLendNum()-itementity.getReturnNum());
//                appLendDetailService.update(lendDetail);
                
//                BizMaterialsManage bizMaterialsManage =  bizMaterialsManageMapper.getById(itementity.getMaterialsId());
//                // 维护实际库存
//                bizMaterialsManage.setStockNum(bizMaterialsManage.getStockNum() + itementity.getReturnNum());
//                //维护可用库存
//                bizMaterialsManage.setEnableStockNum(bizMaterialsManage.getEnableStockNum() + itementity.getReturnNum());
//                bizMaterialsManageMapper.save(bizMaterialsManage);
            }
            
            return ResultCode.SUCCESS;
        } catch (Exception e) {
            log.error("新增物资出库记录失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
	}
	
	@Override
	public JsonResult saveOther(AppReturnDetailForm form, AppMaterialsReturn entity) {
		try {
			JsonResult jr = new JsonResult();
			AppMaterialsLend lend = appMaterialsLendService.getById(entity.getLendId());
			entity.setLendCode(lend.getLendCode());
            entity.setReturnTime(new Date());
            //保存时设置状态为0 待归还
            entity.setReturnStatus("0");
            appmaterialsreturnMapper.save(entity);
            //保存归还明细
            for (AppReturnDetail itementity : form.getItemEntity()) {
            	itementity.setReturnId(entity.getId());
                appReturnDetailMapper.save(itementity);
            }
            jr.setData(entity.getId());
	        jr.setResult(ResultCode.SUCCESS);
			return jr;
        } catch (Exception e) {
            log.error("新增物资归还记录失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
	}

	@Override
	public IResult updateInfo(AppMaterialsReturn entity, List<AppReturnDetail> appReturnDetailList) {
		log.debug("----开始归还----");
		try{
			entity.setReturnStatus("1"); //已还状态,表示已经签署
			int a = 0;//记录已还清的物资数量
			for(AppReturnDetail item : appReturnDetailList){
				// 首先修改相应借出明细的待还数量和状态
				log.debug("----修改出借明细----");
				AppLendDetail queryEntity = new AppLendDetail();
		        queryEntity.setLendId(entity.getLendId());
		        queryEntity.setMaterialsId(item.getMaterialsId());
		        AppLendDetail lendDetail = appLendDetailMapper.queryForObject(queryEntity);
		        BizMaterialsManage materialsManage = materialsManageMapper.getById(item.getMaterialsId());
		        log.debug("【" + materialsManage.getMaterialsName() + "】");
		        log.debug("原有实际库存---->>>>"+ materialsManage.getStockNum());
		        log.debug("原有可用库存---->>>>"+ materialsManage.getEnableStockNum());
		        log.debug("借出数量---->>>>"+ lendDetail.getLendNum());
		        log.debug("需要归还数量---->>>>"+ lendDetail.getNeedReturnNum());
		        int needReturnNum = lendDetail.getNeedReturnNum()-item.getReturnNum();
		        lendDetail.setNeedReturnNum(needReturnNum);
		        log.debug("本次归还了---->>>>" + item.getReturnNum());
		        log.debug("还需归还数量---->>>>" + lendDetail.getNeedReturnNum());
		        if(needReturnNum == 0){  //如果都还清了
		        	lendDetail.setLendStatus("2"); //状态设置为已还
		        	a++;
		        }
		        appLendDetailMapper.update(lendDetail);
		        
		        //修改物资的库存
		        materialsManage.setStockNum(materialsManage.getStockNum() + item.getReturnNum()); //修改实际库存
		        materialsManage.setEnableStockNum(materialsManage.getEnableStockNum() + item.getReturnNum()); //修改可用库存
		        log.debug("归还后的实际库存---->>>>"+ materialsManage.getStockNum());
		        log.debug("归还后的可用库存---->>>>"+ materialsManage.getEnableStockNum());
		        materialsManageMapper.update(materialsManage);
			}
			
			//检查所有的物资是否已经还清，如果还清了将出借记录的状态置为已还
	        //如果所有的出借明细都是已还状态，则将出借记录状态置为已还
			List<AppLendDetail> list1 = appLendDetailMapper.getByLendId(entity.getLendId());
			if(list1.size() == a){
				log.debug("还清了---->>>>");
				AppMaterialsLend lend = appMaterialsLendService.getById(entity.getLendId());
				lend.setLendStatus("2"); 
				appMaterialsLendService.update(lend);
			}
			

			appmaterialsreturnMapper.update(entity); //更新归还记录
			return ResultCode.SUCCESS;
		}catch(Exception e){
			log.error("归还签署后更新数据失败", e);
            throw new ServiceException(ResultCode.ERROR);
        }
		
	}

}